if (typeof HTMLElement != "undefined" && !HTMLElement.prototype.insertAdjacentElement) {
    HTMLElement.prototype.insertAdjacentElement = function (where, parsedNode) {
        switch (where) {
            case 'beforeBegin':
                this.parentNode.insertBefore(parsedNode, this)
                break;
            case 'afterBegin':
                this.insertBefore(parsedNode, this.firstChild);
                break;
            case 'beforeEnd':
                this.appendChild(parsedNode);
                break;
            case 'afterEnd':
                if (this.nextSibling)
                    this.parentNode.insertBefore(parsedNode, this.nextSibling);
                else this.parentNode.appendChild(parsedNode);
                break;
        }
    }
}

if (!window.GestaltMedia) {
    window.GestaltMedia = {};
}
GestaltMedia.__objectCount = 1;
GestaltMedia.downloadStack = {}

// This should be a fully qualified path to the direcotry that contains the 
// Media.xaml and Media.py files for our case this just happens to be the same 
// as our DLR directory, but it does not have to be.
if (!GestaltMedia.path)
    GestaltMedia.path = "http://www.visitmix.com/dlr"; 
    
GestaltMedia.xamlPath = GestaltMedia.path + "/convert.ashx?filename=media.xaml"; // these need to point to JavaScript encoded files
GestaltMedia.pythonPath = GestaltMedia.path + "/convert.ashx?filename=media.py";

if (!GestaltMedia.__loaded) {
    // we need to pause until DLR is done loading
    GestaltMedia.__startup = function () {
        if (!window.DLR || DLR.__loaded != true)
            setTimeout(GestaltMedia.__startup, 1000);
        else
            GestaltMedia.Run();
    }

    GestaltMedia.Run = function() {

        var mediatags = []

        var videotags = document.getElementsByTagName("video");
        var audiotags = document.getElementsByTagName("audio");

        for (videoidx = 0; videoidx < videotags.length; videoidx++) mediatags.push(videotags[videoidx]);
        for (audioidx = 0; audioidx < audiotags.length; audioidx++) mediatags.push(audiotags[audioidx]);

        var nodes = []

        for (mediaidx = 0; mediaidx < mediatags.length; mediaidx++) {

            var tag = mediatags[mediaidx];

            if (tag.tagName == "AUDIO" && navigator.userAgent.indexOf("Chrome") != -1) {
                continue;   // don't try to play audio in chrome since it has it's own HTML5 audio player
            }
            
            var settings = GestaltMedia.parseMediaTag(tag);
            GestaltMedia.InjectSettingsXml(tag, settings);
            var xamltag = GestaltMedia.InjectXamlRef(tag, settings);
            tag.style.display = "none";
            nodes.push(settings);
        }
        GestaltMedia.InjectScriptTag(nodes);
    }

    GestaltMedia.parseMediaTag = function (tag) {
        settings = {}
        settings.sources = []

        if (tag.tagName == "VIDEO") settings["video"] = "true";
        else settings["video"] = "false";

        var attributes = ["id", "src", "width", "height", "skin", "autoplay", "volume", "poster", "loop", "controls", "autobuffer", "muted", "captionareavisible", "captioningenabled", "captionareaheight", "behavior", "controlpanelovermedia"];

        for (attidx = 0; attidx < attributes.length; attidx++) {
            var attval = tag.getAttribute(attributes[attidx]);

            if (attidx == 1) { // if there is a src attribute in the audio/video tag grab it.
                if (attval != null) {
                    settings.sources.push(attval);
                }
            }
            if (attval != null) { // if there is no assignment it is a bool, so set it to true 
                if (attval == "")
                    settings[attributes[attidx]] = "true"
                else
                    settings[attributes[attidx]] = attval;
            }
            else { 
                // if the width and height are not set. set some defaults.
                // TODO: get the actual size of the video and report back to HTML DOM to size properly
                if (attidx == 2)
                    settings[attributes[attidx]] = "300"
                
                if (attidx == 3)
                    settings[attributes[attidx]] = "200"
            }
        }

        if (tag.children.length > 0) {
            // using chrome or FF
            for (i = 0; i < tag.children.length; i++) {
                var srctag = tag.children[i];
                var srcval = srctag.getAttribute("src");
                if (srcval != null) {
                    settings.sources.push(srcval);
                }
            }
        }
        else {
            // using IE
            var srctag = tag.nextSibling;
            while (srctag.tagName == "SOURCE" || srctag.tagName == "/SOURCE") {
                if (srctag.tagName == "SOURCE") {
                    var srcval = srctag.getAttribute("src");
                    if (srcval != null) {
                        settings.sources.push(srcval);
                    }
                }
                srctag = srctag.nextSibling;
            }
        }

        if (settings.id == null) {
            settings.id = "gestaltmedia" + GestaltMedia.__objectCount;
            GestaltMedia.__objectCount++;
        }

        settings.xamlid = settings.id + "-xaml";
        settings.settingsid = settings.id + "-settings";

        return settings;
    }

    GestaltMedia.InjectSettingsXml = function (tag, settings) {
        var settingsXml = GestaltMedia.ToXml(settings);
        var scriptTag = document.createElement("script");
        scriptTag.type = "text/xml";
        scriptTag.id = settings.settingsid;
        scriptTag.text = settingsXml;
        tag.insertAdjacentElement('afterEnd', scriptTag);

        return scriptTag;
    }

    GestaltMedia.InjectXamlRef = function (tag, settings) {
        var scriptTag = document.createElement("script");
        scriptTag.type = "application/xml+xaml";
        scriptTag.id = settings.xamlid;


        if (settings.width != null) scriptTag.setAttribute("width", settings.width);
        if (settings.height != null) scriptTag.setAttribute("height", settings.height);

        if (settings.skin != null) {
            // if a skin is defined use that and get it locally
            scriptTag.src = settings.skin;
            tag.insertAdjacentElement('afterEnd', scriptTag);
        }
        else {
            // Load media.xaml.js from whereever GestaltMedia.path is defined 
            tag.insertAdjacentElement('afterEnd', scriptTag);
            GestaltMedia.jsEncodeDownload(GestaltMedia.xamlPath, "media.xaml", scriptTag.id, null);
        }

        return scriptTag;
    }

    GestaltMedia.InjectScriptTag = function (nodes) {
        // add the script tag, call DLR activations
        var scriptTag = document.createElement("script");
        scriptTag.type = "text/python";

        var classval = "";
        for (i = 0; i < nodes.length; i++) {
            classval += nodes[i].xamlid;
            if (i != nodes.length - 1) classval += ", ";
        }

        if (navigator.appName == "Microsoft Internet Explorer") {
            scriptTag.className = classval;
        }
        else {
            scriptTag.setAttribute("class", classval);
        }

        if (nodes[0].behavior != null) {
            
            // if a behavior is defined use that and get the file locally
            scriptTag.src = nodes[0].behavior;
            document.body.appendChild(scriptTag);

            // Now loop through all of the nodes and call DLR.createSilverlightObject
            for (i = 0; i < nodes.length; i++) {
                // need to translate gestalt settings to dlr settings
                var gsettings = nodes[i];
                var settings = {}; // this is in dlr format
                if (gsettings.width != null) settings.width = gsettings.width;
                if (gsettings.height != null) settings.height = gsettings.height;
                if (gsettings.xamlid != null) settings.xamlid = gsettings.xamlid;

                DLR.__createSilverlightObject(nodes[i].xamlid, DLR.parseSettings(DLR.getSettings(), settings));
            }
        }
        else {
            scriptTag.id = "gestaltmedia-python";

            // Load media.py.js from whereever GestaltMedia.path is defined
            document.body.appendChild(scriptTag);
            GestaltMedia.nodes = nodes;
            GestaltMedia.jsEncodeDownload(GestaltMedia.pythonPath, "media.py", scriptTag.id, GestaltMedia.Activate);
        }

        return scriptTag;
    }

    GestaltMedia.jsEncodeDownload = function (url, filename, id, func) {
        GestaltMedia.downloadStack[filename] = { "id": id, "func": func };
        var scriptTag = document.createElement("script");
        scriptTag.type = "text/javascript";
        // we'll ignore scriptTag.id for now; we might want to set it to allow deletion of tags on complete

        scriptTag.src = url;
        document.body.appendChild(scriptTag);

    }

    GestaltMedia.jsEncodeDownloadFinished = function (filename, body) {
        var info = GestaltMedia.downloadStack[filename];
        var sid = info.id;
        var sTag = document.getElementById(sid);
        sTag.text = body;
        var func = info.func;

        delete GestaltMedia.downloadStack[filename];
        
        if (func != null) func();
    }

    GestaltMedia.Activate = function () {
        // wait for all downloads to complete
        var downloadscount = 0;
        for (fname in GestaltMedia.downloadStack) downloadscount++;

        if (downloadscount > 0){
            setTimeout(GestaltMedia.Activate, 1000);
            return;
        }

        var nodes = GestaltMedia.nodes;
        // TODO: Now loop through all of the nodes and call DLR.createSilverlightObject
        for (i = 0; i < nodes.length; i++) {
            // need to translate gestalt settings to dlr settings
            var gsettings = nodes[i];
            var settings = {}; // this is in dlr format
            if (gsettings.width != null) settings.width = gsettings.width;
            if (gsettings.height != null) settings.height = gsettings.height;
            if (gsettings.xamlid != null) settings.xamlid = gsettings.xamlid;

            DLR.__createSilverlightObject(nodes[i].xamlid, DLR.parseSettings(DLR.getSettings(), settings));
        }
    }

    GestaltMedia.ToXml = function (settings) {
        var settingsXml = "<settings>\r\n";
        for (var attr in settings) {
            if (attr != "sources") {
                settingsXml += "<" + attr + ">";
                settingsXml += GestaltMedia.XmlEncode(settings[attr]);
                settingsXml += "</" + attr + ">\r\n";
            }
        }
        settingsXml += "<sources>";
        for (i = 0; i < settings.sources.length; i++) {
            settingsXml += "<source>" + GestaltMedia.XmlEncode(settings.sources[i]) + "</source>\r\n";
        }
        settingsXml += "</sources>\r\n";
        settingsXml += "</settings>";
        return settingsXml;
    }

    GestaltMedia.XmlEncode = function (val) {
        val = val.replace(/&/g, "&amp;");
        val = val.replace(/</g, "&lt;");
        val = val.replace(/>/g, "&gt;");
        val = val.replace(/'/g, "&apos;");
        val = val.replace(/"/g, "&quot;");
        return val;
    }

    GestaltMedia.__loaded = true;
}

if(window.addEventListener) {
    window.addEventListener('load', GestaltMedia.__startup, false);
} else {
    window.attachEvent('onload', GestaltMedia.__startup);
}